<?php

namespace app\common\letterbusiness\upload;

use app\extra\UpyunSDK\Upload as upyunSDK;
use think\Config;

class Upload {

    public static function UpYunUpload($originFile) {
        $upyun = new upyunSDK();
        $result = $upyun->writeFile($originFile);
        return $result;
    }

    public static function UpYunUploadurl($post) {
        $upyun = new upyunSDK();
        $result = $upyun->writeFileUrl($post);
        return $result;
    }

    /*
     *
     * 上传图片到upyun
     *
     */

    public static function uploadav($base64_img, $isbase64 = true) {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            $type = $result[2];
            $file = "./static/image/";
            if (!file_exists($file))
                mkdir($file);
            $new_file = $file . md5($base64_img) . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                $upyunResult = self::UpYunUpload($new_file);
                $resourceHost = Configbn::get('upyun.resourcesHost');
                $data = array(
                    'dest_file_name' => $upyunResult['dest_file_name'] ? $resourceHost . $upyunResult['dest_file_name'] : '',
                    'status' => 1,
                    'resource_host' => $resourceHost
                );
                if (file_exists($new_file)) {
                    unlink($new_file); //上传到又拍云后删除本地服务器图片
                }
                return $data;
            } else {
                throw new \Exception("上传失败", 103);
            }
        } else {
            throw new \Exception("图片参数格式不正确", 104);
        }
    }

    /*
     *
     * 数组方式上传图片到upyun
     *
     */

    public static function uploadavarray($base64_imgarray, $isbase64 = true) {
        $returnarray = '';
        $data = array();
        $array = explode("data:image/", $base64_imgarray);
        foreach ($array as $base64_img) {
            $base64array = explode('"', $base64_img);
            foreach ($base64array as $base64_imgt) {
                $image = "data:image/" . $base64_imgt;
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {

                    file_put_contents('test3.txt', $image);
                    $type = $result[2];
                    $file = "./static/image/";
                    if (!file_exists($file)) {
                        mkdir($file);
                    }
                    $new_file = $file . md5($image) . ".{$type}";
                    if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $image)))) {
                        $upyunResult = self::UpYunUpload($new_file);
                        $resourceHost = Configbn::get('upyun.resourcesHost');
                        $data = array(
                            'dest_file_name' => $upyunResult['dest_file_name'] ? $resourceHost . $upyunResult['dest_file_name'] : '',
                            'status' => 1,
                            'resource_host' => $resourceHost
                        );
                        if (file_exists($new_file)) {
                            unlink($new_file); //上传到又拍云后删除本地服务器图片
                        }
                    }
                }
            }
            if (isset($data['dest_file_name']) && !empty($data['dest_file_name'])) {
                $returnarray[] = isset($data['dest_file_name']) ? $data['dest_file_name'] : "";
            }
        }
        $return = json_encode($returnarray);
        return $return;
    }

    /*
     *
     * 上传图片到upyun
     *
     */

    public static function uploadavurl($post) {
        $upyunResult = self::UpYunUploadurl($post);
        $resourceHost = config('upyun')['resourcesHost']; 
        $data = array(
            'dest_file_name' => $upyunResult['dest_file_name'] ? $resourceHost . $upyunResult['dest_file_name'] : '',
            'status' => 1,
            'resource_host' => $resourceHost
        );
        return $data;
        //  } else {
        //  throw new \Exception("上传失败", 103);
        // }
    }

    /**
     * 获取远程图片
     * 
     * @param string $url
     * @param string $method
     * @param array $params
     * @param int $timeout
     * @return boolean
     */
    public static function _requestgetimg($url, $method = "GET", $params = array(), $timeout = 30, $extParams = array()) {
        $url = $url;
        $paramString = http_build_query($params, '', '&');
        if (strtoupper($method) == "GET" && $params) {
            $url .= "?" . $paramString;
        }
        $ch = curl_init($url);

        if (strtoupper($method) == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paramString);
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        if (!empty($extParams['headers'])) {
            $headerArr = array();
            foreach ($extParams['headers'] as $k => $v) {
                $headerArr[] = $k . ':' . $v;
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
        }

        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

        if (!empty($extParams["cookies"])) {
            curl_setopt($ch, CURLOPT_COOKIE, $this->analyzeCookie($extParams["cookies"]));
        }
        //检测是否是https访问
        if (strpos($url, 'https') === 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $result['body'] = curl_exec($ch);
        $result['header'] = curl_getinfo($ch);
        curl_close($ch);
        return $result;
    }

}
